package com.jsz.peini.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.jsz.peini.redis.util.UserRedisUtil;
import com.sun.org.apache.xml.internal.security.Init;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;

public class AppSecretUtil {
	private static final Logger logger = LoggerFactory.getLogger(AppSecretUtil.class);
	private static int g = 1000001;
	private static int p = 3000;
	public static HashMap<String,Object> sceMap = new HashMap<String,Object>();
	
	private static String startStr = "cnbj";
	private static String endStr = "arh6m";
	private static String aesPass = "24jsz21sjzhb2017";
	
	public static String getAppA(String appAStr){
		
		byte[] result;
		try {
			//result = base64Decode(appAStr.getBytes("utf-8"));
			//result = Base64.decode(appAStr);
			appAStr = aesDecrypt(appAStr);
			if(!appAStr.contains(startStr)){
				return null;
			}
			
			if(!appAStr.contains(endStr)){
				return null;
			}
			
			appAStr = appAStr.replace(startStr, "");
			appAStr = appAStr.replace(endStr, "");
			return appAStr;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return null;
	}

	/**
	 * @param userId 用户id
	 * @param appA 手机端素数加密值
	 * @return 返回给手机端的素数加密值
	 * 分享,支付,充值,广告点击,提现
	 * bg=5:x,y小于54
	 * bg=6:x,y小于48 
	 */
	public static String getAppSecret(String userId,String appAStr){
		int y = (int)(Math.random()*2999)+1;
		
		int appA = 0;
		
		/*appAStr = aesDecrypt(appAStr.getBytes());
		if(!appAStr.contains(startStr)){
			return "";
		}
		
		if(!appAStr.contains(endStr)){
			return "";
		}
		
		appAStr = appAStr.replace(startStr, "");
		appAStr = appAStr.replace(endStr, "");*/
		appA = Integer.parseInt(appAStr);
		
		int appToken = appA^y;
		
		//放入redis缓存
		UserRedisUtil.updateUserSecuToken(userId, String.valueOf(appToken));
		
		int serverB = g^y%p;
		
		String secuStr = startStr+serverB+endStr;
		secuStr = aesEncrypt(secuStr);
		
		return secuStr;
	}
	
	/**
	 * 验证appToken是否正确
	 */
	public static boolean valAppToken(String userid,String appToken){
		/*if(!sceMap.containsKey(userid)){
			return false;
		}
		String token = MDUtil.encodePwd(String.valueOf(sceMap.get(userid)));*/
		Integer sceToken = UserRedisUtil.getUserSecuToken(userid);
		if(sceToken == null){
			return false;
		}
		String token = MDUtil.encodePwd(String.valueOf(sceToken));
		
		if(appToken.equals(token)){
			return true;
		}else{
			return false;
		}
		//return sceMap.containsKey(userid)?appToken.equals(MDUtil.encodePwd(String.valueOf(sceMap.get(userid)))):false;
	}
	
	public static final String VIPARA = "1269571569321021";  
	
	/** 
	 * 加密 
	 *  
	 * @param content 需要加密的内容 
	 * @param password  加密密码 
	 * @return 
	 */
	public static String aesEncrypt(String content) {  
        try {   
        	IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());  
            SecretKeySpec key = new SecretKeySpec(aesPass.getBytes(), "AES");  
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);  
            byte[] result = cipher.doFinal(content.getBytes("utf-8"));  
            
               /* KeyGenerator kgen = KeyGenerator.getInstance("AES");  
                kgen.init(128, new SecureRandom(aesPass.getBytes("utf-8")));  
                SecretKey secretKey = kgen.generateKey();  
                byte[] enCodeFormat = secretKey.getEncoded();  
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
                byte[] byteContent = content.getBytes("utf-8");
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化  
                byte[] result = cipher.doFinal(byteContent);  */
                //return base64Encode(result); // 加密
                return Base64.encode(result);
        } catch (NoSuchAlgorithmException e) {  
                logger.error(e.getMessage(),e);  
        } catch (NoSuchPaddingException e) {  
                logger.error(e.getMessage(),e);  
        } catch (InvalidKeyException e) {  
                logger.error(e.getMessage(),e);  
        } catch (UnsupportedEncodingException e) {  
                logger.error(e.getMessage(),e);  
        } catch (IllegalBlockSizeException e) {  
                logger.error(e.getMessage(),e);  
        } catch (BadPaddingException e) {  
                logger.error(e.getMessage(),e);  
        } catch (InvalidAlgorithmParameterException e) {
			logger.error(e.getMessage(),e);
		}  
        return null;  
	}  
	
	public static String base64Encode(byte[] bytes) {
        return new BASE64Encoder().encode(bytes);
    }
	
	public static byte[] base64Decode(byte[] bytes) {
        try {
			return new BASE64Decoder().decodeBuffer(new String(bytes));
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
        return null;
    }

	
	/**解密 
	 * @param content  待解密内容 
	 * @param password 解密密钥 
	 * @return 
	 */  
	public static String aesDecrypt(String content) {  
	        try {  
	                 /*KeyGenerator kgen = KeyGenerator.getInstance("AES");  
	                 kgen.init(128, new SecureRandom(aesPass.getBytes()));  
	                 SecretKey secretKey = kgen.generateKey();  
	                 byte[] enCodeFormat = secretKey.getEncoded();  
	                 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");              
	                 Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
	                cipher.init(Cipher.DECRYPT_MODE, key);// 初始化  
	                byte[] result = cipher.doFinal(content); */
	        	Init.init();
	        	byte[] byteMi = Base64.decode(content);  
//	          byte[] byteMi=  str2ByteArray(content);  
	            IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());  
	            SecretKeySpec key = new SecretKeySpec(aesPass.getBytes(), "AES");  
	            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
	            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);  
	            byte[] result = cipher.doFinal(byteMi);
	            //byte[] result = cipher.doFinal(content);  
	                return new String(result); // 加密  
	        } catch (NoSuchAlgorithmException e) {  
	                logger.error(e.getMessage(),e);  
	        } catch (NoSuchPaddingException e) {  
	                logger.error(e.getMessage(),e);  
	        } catch (InvalidKeyException e) {  
	                logger.error(e.getMessage(),e);  
	        } catch (IllegalBlockSizeException e) {  
	                logger.error(e.getMessage(),e);  
	        } catch (BadPaddingException e) {  
	                logger.error(e.getMessage(),e);  
	        } catch (InvalidAlgorithmParameterException e) {
				logger.error(e.getMessage(),e);
			} catch (Base64DecodingException e) {
				logger.error(e.getMessage(),e);
			}  
	        return null;  
	}  
	
	public static void main(String[] args) {
		/*int a;
		int b;
		//int x=(int)(Math.random()*2999)+1;
		int x = 1000;
		a = g^x%p;
		b = Integer.parseInt(getAppSecret("1333", a));
		*/
		int a;
		int x=(int)(Math.random()*2999)+1;
		a = g^x%p;
		
		String appA = startStr+a+endStr;
		logger.info(appA);
		
		String aa = aesEncrypt(appA);
	}
	
	/**
	 * shutdown.sh shutdown.bat触发 
	 */
	public static class tomcatClose implements ServletContextListener {

		@Override
		public void contextDestroyed(ServletContextEvent arg0) {
			//tomcat关闭前的一些数据处理
		}

		@Override
		public void contextInitialized(ServletContextEvent arg0) {
			//tomcat打开前的一些数据处理
			
		}

	}
}
